<template>
  <el-dropdown trigger="click" @command="setupLocale">
    <button @click="toggleRotation" class="flex items-center">
      <div class="flex">
        <template v-if="locale === 'zh'">
          <Image class="flag mr-2" name="cn" height="12" />
          {{ $t('language_zh') }}
        </template>
        <template v-else>
          <Image class="flag mr-2" name="usa" height="12" />
          {{ $t('language_en') }}
        </template>
      </div >
      <span class="ml-4" :class="{ 'rotated': isRotated }">
        <SVGIcon type="select"/>
      </span>
    </button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="zh">
          <Image class="mr-2" name="cn" height="12" />
          {{ $t('language_zh') }}
        </el-dropdown-item>
        <el-dropdown-item command="en">
          <Image class="mr-2" name="usa" height="12" />
          {{ $t('language_en') }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'

const { locale } = useI18n()
const isRotated = ref(false)

onMounted(() => {
  const savedLocale = localStorage.getItem('locale')
  if (savedLocale) {
    locale.value = savedLocale
  }
})

const setupLocale = (lang) => {
  locale.value = lang
  localStorage.setItem('locale', lang)
}

const toggleRotation = () => {
  isRotated.value = !isRotated.value
}
</script>

<style lang="scss" scoped>
.flag {
  transform: translateY(1px);
}

.pull-down {
  transition: transform 0.3s ease; 
}

.rotated {
  transform: translateY(1px) rotate(180deg); 
}

button {
  height: 27px;
  padding: 14px 4px;
  border-radius: calc(var(--el-radius) / 2);
  border: 1px solid var(--el-border-color);
}
</style>
